﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using WeChatParking.Core;
using WeChatParking.Entity;

namespace WeChatParking.Web.UrlAuthorize
{
    /// <summary>
    /// Account Helper
    /// </summary>
    public static class AccountHelper
    {
        /// <summary>
        /// Get all permission list
        /// </summary>
        /// <returns>Permission List</returns>
        public static List<Permission> GetPermissionItems()
        {
            if (HttpContext.Current.Cache["PermissionItems"] == null)
            {
                UrlAuthorizeEntities db = new UrlAuthorizeEntities();
                HttpContext.Current.Cache["PermissionItems"] = db.PermissionItems.ToList(); ;
            }

            return (List<Permission>)HttpContext.Current.Cache["PermissionItems"];
        }

        /// <summary>
        /// Get User Permission
        /// </summary>
        /// <param name="userID">User ID</param>
        /// <returns>User Permission Array</returns>
        public static Int32[] GetUserPermission(int userID, int EnterprisesID)
        {
            if (HttpContext.Current.Session["Permission"] == null)
            {
                UrlAuthorizeEntities db = new UrlAuthorizeEntities();
                int RoleID = db.User_info.Where(c => c.UserId == userID && c.EnterpriseID == EnterprisesID).Select(c => c.RoleID).ToArray()[0];
                var permissions = db.PermissionList.FirstOrDefault(c => c.ID == RoleID && c.EnterpriseID == EnterprisesID);
                if (permissions==null)
                    return null;
                //string[] permissions = (db.PermissionList.Where(c => c.ID == RoleID).Select(c => c.PermissionID)).ToString().Split(',');
                HttpContext.Current.Session["Permission"] = StringToint(permissions.PermissionID.Split(','));
            }
            return (Int32[])HttpContext.Current.Session["Permission"];
        }
        private static Int32[] StringToint(string[] v)
        {
            int length = v.Length;
            Int32[] data = new Int32[length];
            for (int i = 0; i < length; i++)
            {
                data[i] = Convert.ToInt32(v[i]);
            }
            return data;
        }
    }
}